
import json
from django.shortcuts import render, get_object_or_404
from django.views.generic.base import View
from django.http import HttpResponse
from django.conf import settings
from django.db.models import Q
from django.core.exceptions import ObjectDoesNotExist

from django import forms

from criterion.models import ReviewKey
from system.models import SystemSetup
from utils.mixin_utils import LoginRequiredMixin
from rbac.models import Menu
from django.core.serializers.json import DjangoJSONEncoder

from .models import Category,News,News2User
from django.contrib.auth import get_user_model

User = get_user_model()

class NewsView(LoginRequiredMixin, View):
    """
    通知新闻管理
    """
    def get(self, request):
        ret = Menu.getMenuByRequestUrl(url=request.path_info)
        ret.update(SystemSetup.getSystemSetupLastData())
        return render(request, 'news/news_announcement.html', ret)

class NewsListJsonView(LoginRequiredMixin, View):
    """
    获取组织架构数据列表
    """
    def get(self, request):
        fields = ['id', 'title', 'content', 'pubdate', 'category__name', 'category_id']
        ret = dict(data=list(News.objects.values(*fields)))
        for i in ret["data"]:
            name = ''
            i['pubdate'] = str(i['pubdate']).replace(' ', '&nbsp')
            i['title'] = i['title']+','+str(i['id'])
            field = ['users__name']
            a = list(News.objects.values(*field).filter(id=i['id']))
            for n in a:
                # uname=n['users__name']+' '
                uname=' '
                name+=uname
            i['users'] = name
        return HttpResponse(json.dumps(ret, cls=DjangoJSONEncoder), content_type='application/json')

class NewsDetailView(LoginRequiredMixin, View):
    """
    组织架构详情页：查看、修改、新建数据
    """
    def get(self, request):
        ret = dict()
        if 'id' in request.GET and request.GET['id']:
            structure = get_object_or_404(News, pk=request.GET.get('id'))
            structures = News.objects.exclude(id=request.GET.get('id'))
            ret['structure'] = structure
        else:
            structures = News.objects.all()
        ret['structures'] = structures
        data = Category.objects.all()
        _list = []
        for i in data:
            _list.append({
                'c_id': i.id,
                'name': i.name
            })
        ret['categorys'] = _list
        # fields = ['id', 'name']
        # ret['users'] = list(User.objects.values(*fields))
        # field = ['users__id']
        # if 'id' in request.GET:
        #     t_id = News.objects.values(*field).filter(id=request.GET['id'])
        #     ret['p_user'] = User.objects.values(*fields).filter(id=int(t_id[0]['users__id']))[0]
        return render(request, 'news/news_add.html', ret)

    def post(self, request):
        res = dict(result=False)
        if 'id' in request.POST and request.POST['id']:
            structure = get_object_or_404(News, pk=request.POST.get('id'))
        else:
            structure = News()
        structure_update_form = NewsUpdateForm(request.POST, instance=structure)
        if structure_update_form.is_valid():
            structure_update_form.save()
            if not request.POST['id']:
                user = News.objects.order_by('-id')[:1].get()
                a = User.objects.all()
                user.author_id = int(request.session.get('_auth_user_id'))
                user.save()
                for i in a:
                    user.users.add(i)
                res['result'] = True
        return HttpResponse(json.dumps(res), content_type='application/json')

class NewsDeleteView(LoginRequiredMixin, View):
    """
    删除数据支持删除单条记录和批量删除
    """
    def post(self, request):
        ret = dict(result=False)
        if 'id' in request.POST and request.POST['id']:
            for i in request.POST.get('id').split(','):
                News2User.objects.filter(news_id=int(i)).delete()
                News.objects.filter(id=int(i)).delete()
            ret['result'] = True
        return HttpResponse(json.dumps(ret), content_type='application/json')

class NewsShowView(LoginRequiredMixin, View):
    """
    显示通知
    """
    def get(self, request):
        fields = ['id', 'content']
        _list = dict(data=list(News.objects.values(*fields)))
        ret = {}
        if 'id' in request.GET and request.GET['id']:
            for i in _list['data']:
                if i['id'] == int(request.GET['id']):
                    ret['data'] = i['content']
        return render(request, 'news/news_show.html', ret)

# class NewsVisibleView(LoginRequiredMixin, View):
#     """
#     分配条款（条款下所有要点）或要点给用户
#     """
#     def get(self, request):
#         nids=request.GET['id']
#         fields = ['users__id']
#         user = News.objects.values(*fields).filter(id=int(nids))
#         all_users = User.objects.all()
#         return render(request, 'news/news_visible.html', locals())
#
#     def post(self, request):
#         res = dict(result=False)
#         if 'uids' in request.POST and request.POST['uids']:
#             print('nids:', request.POST['nids'])
#             print('uids:', request.POST.getlist('uids', []))
#             for u in request.POST.getlist('uids', []):
#                 user = News.objects.get(id=int(request.POST['nids']))
#                 a = User.objects.get(id=int(u))
#                 user.users.add(a)
#                 user.save()
#         res['result'] = True
#         return HttpResponse(json.dumps(res), content_type='application/json')

class NewsUpdateForm(forms.ModelForm):
    class Meta:
        model = News
        fields = ['title', 'content',  'category', 'pubdate']

class NewsCategoryView(LoginRequiredMixin, View):
    """
    通知分类管理
    """
    def get(self, request):
        ret = Menu.getMenuByRequestUrl(url=request.path_info)
        ret.update(SystemSetup.getSystemSetupLastData())
        return render(request, 'news/news_category.html', ret)

class NewsCategoryListJsonView(LoginRequiredMixin, View):
    """
    获取通知数据列表
    """
    def get(self, request):
        fields = ['id', 'name']
        ret = dict(data=list(Category.objects.values(*fields)))
        for i in ret['data']:
            newsamount=News.objects.filter(category__name=i['name']).count()
            i['newsamount'] = newsamount
        return HttpResponse(json.dumps(ret, cls=DjangoJSONEncoder), content_type='application/json')

class NewsCategoryAddView(LoginRequiredMixin, View):
    """
    增加分类
    """
    def get(self, request):
        ret = dict()
        if 'id' in request.GET and request.GET['id']:
            structure = get_object_or_404(Category, pk=request.GET.get('id'))
            structures = Category.objects.exclude(id=request.GET.get('id'))
            ret['structure'] = structure
        else:
            structures = Category.objects.all()
        ret['structures'] = structures
        return render(request, 'news/news_category_add.html', ret)

    def post(self, request):
        res = dict(result=False)
        if 'id' in request.POST and request.POST['id']:
            structure = get_object_or_404(Category, pk=request.POST.get('id'))
        else:
            structure = Category()
        data = Category.objects.all()
        flag = True
        for i in data:
            if i.name == request.POST['name']:
                flag = False
        if flag:
            structure_update_form = NewsCategoryUpdate(request.POST, instance=structure)
            if structure_update_form.is_valid():
                structure_update_form.save()
                res['result'] = True
        else:
            res['result'] = False
        return HttpResponse(json.dumps(res), content_type='application/json')

class NewsCategoryRenameView(LoginRequiredMixin, View):
    """
    增加分类
    """
    def get(self, request):
        ret = dict()
        if 'id' in request.GET and request.GET['id']:
            structure = get_object_or_404(Category, pk=request.GET.get('id'))
            structures = Category.objects.exclude(id=request.GET.get('id'))
            ret['structure'] = structure
        else:
            structures = Category.objects.all()
        ret['structures'] = structures
        return render(request, 'news/news_category_rename.html', ret)

    def post(self, request):
        res = dict(result=False)
        if 'id' in request.POST and request.POST['id']:
            structure = get_object_or_404(Category, pk=request.POST.get('id'))
        else:
            structure = Category()
        structure_update_form = NewsCategoryUpdate(request.POST, instance=structure)
        if structure_update_form.is_valid():
            structure_update_form.save()
            res['result'] = True
        return HttpResponse(json.dumps(res), content_type='application/json')

class NewsCategoryDeleteView(LoginRequiredMixin, View):
    """
    删除分类
    """
    def post(self, request):
        ret = dict(result=False)
        if 'id' in request.POST and request.POST['id']:
            id_list = map(int, request.POST.get('id').split(','))
            data = Category.objects.filter(id__in=id_list)
            for i in data:
                News.objects.filter(category__name=i.name).delete()
            data.delete()
            ret['result'] = True
        return HttpResponse(json.dumps(ret), content_type='application/json')

class NewsCategoryUpdate(forms.ModelForm):
    class Meta:
        model = Category
        fields = ['name']
